#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
主题管理系统
支持亮色和暗色两种主题
"""

import tkinter as tk
from tkinter import ttk


class ThemeManager:
    """主题管理器"""
    
    def __init__(self):
        self.current_theme = "light"
        self.themes = {
            "light": {
                "name": "亮色主题",
                "bg": "#fafafa",
                "fg": "#212121",
                "select_bg": "#1976d2",
                "select_fg": "#ffffff",
                "button_bg": "#ffffff",
                "button_fg": "#424242",
                "entry_bg": "#ffffff",
                "entry_fg": "#212121",
                "frame_bg": "#fafafa",
                "text_bg": "#ffffff",
                "text_fg": "#212121",
                "log_bg": "#ffffff",
                "log_fg": "#212121",
                "log_info": "#1976d2",
                "log_success": "#388e3c",
                "log_warning": "#f57c00",
                "log_error": "#d32f2f",
                "progress_bg": "#e0e0e0",
                "progress_fg": "#1976d2",
                "tree_bg": "#ffffff",
                "tree_fg": "#212121",
                "tree_select_bg": "#1976d2",
                "tree_select_fg": "#ffffff"
            },
            "dark": {
                "name": "暗色主题",
                "bg": "#121212",
                "fg": "#e0e0e0",
                "select_bg": "#1976d2",
                "select_fg": "#ffffff",
                "button_bg": "#2c2c2c",
                "button_fg": "#e0e0e0",
                "entry_bg": "#1e1e1e",
                "entry_fg": "#e0e0e0",
                "frame_bg": "#121212",
                "text_bg": "#1e1e1e",
                "text_fg": "#e0e0e0",
                "log_bg": "#1e1e1e",
                "log_fg": "#e0e0e0",
                "log_info": "#64b5f6",
                "log_success": "#81c784",
                "log_warning": "#ffb74d",
                "log_error": "#e57373",
                "progress_bg": "#2c2c2c",
                "progress_fg": "#1976d2",
                "tree_bg": "#1e1e1e",
                "tree_fg": "#e0e0e0",
                "tree_select_bg": "#1976d2",
                "tree_select_fg": "#ffffff"
            }
        }
    
    def get_theme(self, theme_name=None):
        """获取主题配置"""
        if theme_name is None:
            theme_name = self.current_theme
        return self.themes.get(theme_name, self.themes["light"])
    
    def set_theme(self, theme_name):
        """设置当前主题"""
        if theme_name in self.themes:
            self.current_theme = theme_name
            return True
        return False
    
    def get_available_themes(self):
        """获取可用主题列表"""
        return [(name, config["name"]) for name, config in self.themes.items()]
    
    def apply_theme_to_widget(self, widget, widget_type="default"):
        """将主题应用到控件"""
        theme = self.get_theme()
        
        try:
            if isinstance(widget, tk.Tk) or isinstance(widget, tk.Toplevel):
                widget.configure(bg=theme["bg"])
            
            elif isinstance(widget, tk.Frame) or isinstance(widget, ttk.Frame):
                if hasattr(widget, 'configure'):
                    try:
                        widget.configure(bg=theme["frame_bg"])
                    except tk.TclError:
                        pass  # ttk.Frame 不支持 bg 参数
            
            elif isinstance(widget, tk.Label) or isinstance(widget, ttk.Label):
                try:
                    widget.configure(bg=theme["bg"], fg=theme["fg"])
                except tk.TclError:
                    pass  # ttk控件可能不支持某些属性
            
            elif isinstance(widget, tk.Button) or isinstance(widget, ttk.Button):
                try:
                    widget.configure(bg=theme["button_bg"], fg=theme["button_fg"])
                except tk.TclError:
                    pass
            
            elif isinstance(widget, tk.Entry) or isinstance(widget, ttk.Entry):
                try:
                    widget.configure(bg=theme["entry_bg"], fg=theme["entry_fg"])
                except tk.TclError:
                    pass
            
            elif isinstance(widget, tk.Text):
                widget.configure(
                    bg=theme["text_bg"], 
                    fg=theme["text_fg"],
                    selectbackground=theme["select_bg"],
                    selectforeground=theme["select_fg"]
                )
            
            elif isinstance(widget, ttk.Treeview):
                style = ttk.Style()
                style.configure("Treeview",
                              background=theme["tree_bg"],
                              foreground=theme["tree_fg"],
                              fieldbackground=theme["tree_bg"])
                style.configure("Treeview.Heading",
                              background=theme["button_bg"],
                              foreground=theme["button_fg"])
        
        except Exception:
            pass  # 忽略主题应用错误，不影响程序运行
    
    def configure_log_tags(self, text_widget):
        """配置日志文本标签的颜色"""
        theme = self.get_theme()
        
        text_widget.tag_configure('info', foreground=theme["log_info"])
        text_widget.tag_configure('success', foreground=theme["log_success"], font=('Consolas', 9, 'bold'))
        text_widget.tag_configure('warning', foreground=theme["log_warning"], font=('Consolas', 9, 'bold'))
        text_widget.tag_configure('error', foreground=theme["log_error"], font=('Consolas', 9, 'bold'))


class ThemedUIComponents:
    """支持主题的UI组件混入类"""
    
    def init_theme(self):
        """初始化主题管理器"""
        self.theme_manager = ThemeManager()
    
    def apply_theme(self):
        """应用主题到所有控件"""
        theme = self.theme_manager.get_theme()
        
        # 应用到主窗口
        self.root.configure(bg=theme["bg"])
        
        # 应用到日志文本框
        if hasattr(self, 'log_text'):
            self.log_text.configure(
                bg=theme["log_bg"], 
                fg=theme["log_fg"],
                selectbackground=theme["select_bg"],
                selectforeground=theme["select_fg"]
            )
            self.theme_manager.configure_log_tags(self.log_text)
        
        # 配置ttk样式
        style = ttk.Style()
        
        # 应用到TreeView控件 - 现代化设计
        try:
            style.configure("Treeview",
                          background=theme["tree_bg"],
                          foreground=theme["tree_fg"],
                          fieldbackground=theme["tree_bg"],
                          borderwidth=0,
                          relief="flat",
                          rowheight=25)
            style.configure("Treeview.Heading",
                          background=theme["button_bg"],
                          foreground=theme["button_fg"],
                          borderwidth=0,
                          relief="flat",
                          padding=(8, 5))
            style.map("Treeview", 
                     background=[('selected', theme["select_bg"])],
                     foreground=[('selected', theme["select_fg"])])
            style.map("Treeview.Heading",
                     background=[('active', theme["select_bg"])])
        except Exception:
            pass
        
        # 应用到进度条 - 现代化样式
        try:
            style.configure("TProgressbar",
                          background=theme["progress_fg"],
                          troughcolor=theme["progress_bg"],
                          borderwidth=0,
                          lightcolor=theme["progress_fg"],
                          darkcolor=theme["progress_fg"])
        except Exception:
            pass
        
        # 应用到按钮 - 添加圆角和现代化样式
        try:
            style.configure("TButton",
                          background=theme["button_bg"],
                          foreground=theme["button_fg"],
                          focuscolor=theme["select_bg"],
                          borderwidth=0,
                          relief="flat",
                          padding=(12, 8))
            style.map("TButton",
                     background=[('active', theme["select_bg"]),
                               ('pressed', theme["select_bg"])],
                     relief=[('pressed', 'flat'),
                           ('active', 'flat')])
        except Exception:
            pass
        
        # 应用到标签页 - 现代化设计
        try:
            style.configure("TNotebook",
                          background=theme["bg"],
                          borderwidth=0,
                          tabmargins=[0, 5, 0, 0])
            style.configure("TNotebook.Tab",
                          background=theme["button_bg"],
                          foreground=theme["button_fg"],
                          padding=[15, 8],
                          borderwidth=0,
                          focuscolor="none")
            style.map("TNotebook.Tab",
                     background=[('selected', theme["select_bg"]),
                               ('active', theme["select_bg"])],
                     foreground=[('selected', theme["select_fg"]),
                               ('active', theme["select_fg"])],
                     expand=[('selected', [1, 1, 1, 0])])
        except Exception:
            pass
        
        # 应用到输入框 - 现代化样式
        try:
            style.configure("TEntry",
                          fieldbackground=theme["entry_bg"],
                          foreground=theme["entry_fg"],
                          bordercolor=theme["button_bg"],
                          lightcolor=theme["select_bg"],
                          darkcolor=theme["button_bg"],
                          borderwidth=1,
                          relief="solid",
                          padding=(8, 6))
        except Exception:
            pass
        
        # 应用到复选框
        try:
            style.configure("TCheckbutton",
                          background=theme["bg"],
                          foreground=theme["fg"],
                          focuscolor=theme["select_bg"])
            style.map("TCheckbutton",
                     background=[('active', theme["bg"])])
        except Exception:
            pass
        
        # 应用到标签
        try:
            style.configure("TLabel",
                          background=theme["bg"],
                          foreground=theme["fg"])
        except Exception:
            pass
        
        # 应用到框架 - 添加圆角效果
        try:
            style.configure("TFrame",
                          background=theme["bg"],
                          borderwidth=0,
                          relief="flat")
            style.configure("TLabelFrame",
                          background=theme["bg"],
                          foreground=theme["fg"],
                          borderwidth=1,
                          relief="solid",
                          padding=(10, 10))
            style.configure("TLabelFrame.Label",
                          background=theme["bg"],
                          foreground=theme["fg"],
                          padding=(5, 0))
        except Exception:
            pass
        
        # 应用到滚动条
        try:
            style.configure("Vertical.TScrollbar",
                          background=theme["button_bg"],
                          troughcolor=theme["bg"],
                          bordercolor=theme["button_bg"],
                          arrowcolor=theme["fg"],
                          darkcolor=theme["button_bg"],
                          lightcolor=theme["button_bg"])
        except Exception:
            pass
        
        # 应用到窗格
        try:
            style.configure("TPanedwindow",
                          background=theme["bg"])
        except Exception:
            pass
    
    def switch_theme(self):
        """切换主题"""
        current = self.theme_manager.current_theme
        new_theme = "dark" if current == "light" else "light"
        
        self.theme_manager.set_theme(new_theme)
        self.apply_theme()
        
        # 强制刷新界面
        self.root.update_idletasks()
        
        theme_name = self.theme_manager.get_theme()["name"]
        self.add_log(f"[INFO] 已切换到{theme_name}", 'info')
    
    def get_current_theme_name(self):
        """获取当前主题名称"""
        return self.theme_manager.get_theme()["name"]